class Task {
  constructor() {
    this.maxTask = 10;
    this.list = {
      willList: [],
      failList: [],
      runningList: []
    };
  }

  add(task) {
    this.list.willList.push(task);
    this.run();
  }
  run() {
    let { willList, runningList, failList } = this.list;
    if (willList.length && runningList.length < this.maxTask) {
      let tempTask = willList.shift();
      runningList.push(tempTask);
      tempTask().then(
        res => {
          runningList.splice(runningList.indexOf(runningList), 1);
          console.log(
            '剩余:',
            willList.length,
            '正在运行:',
            runningList.length
          );
          this.run();
        },
        () => {
          runningList.splice(runningList.indexOf(runningList), 1);
          console.log(
            '剩余:',
            willList.length,
            '正在运行:',
            runningList.length
          );
          failList.push(tempTask);
        }
      );
    }
  }
}
module.exports = new Task();
